import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import installElementPlus from './plugins/element';
import initRoutes from '@/api/initRoutes';

// 路由守卫：在每一个页面上动态加载菜单
router.beforeEach((to, from, next) => {
  // https://blog.csdn.net/weixin_33815613/article/details/88803600
  console.log('from:', from.path, '   to:', to.path);
  if (to.path === '/') {
    next();
  } else {
    console.log('store.state.routes = ', store.state.routes);
    if (store.state.routes && store.state.routes.length > 0) {
      next();
    } else {
      console.log('重新addRoutes前 router.routes = ', router.getRoutes());
      const storeUserRoutes = window.sessionStorage.getItem('LOGIN_USER_DATA');
      if (storeUserRoutes) {
        const newRoutesData = JSON.parse(storeUserRoutes);
        // newRoutesData.forEach((item: any) => {
        //   const formatedRoute = {
        //     path: item.path,
        //     name: item.name,
        //     component: () => {
        //       return import('./components/' + item.component + '.vue');
        //       // return import('../components/MyComponent.vue');
        //     }
        //   };
        //   router.addRoute(formatedRoute);
        // });
        // store.commit('LOGIN_USER_DATA', newRoutesData);
        initRoutes(newRoutesData);
      }
      console.log('addRoutes后 router.routes = ', router.getRoutes());
      next({ ...to, path: to.path });
    }
  }
});

const app = createApp(App);
installElementPlus(app);
app.use(store).use(router).mount('#app');
